package com.javalab._7thread._3Lock._3JUC._1Lock;

import java.util.Random;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class CommonData {
    /**
     * 读写锁
     * 可重入
     */
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private int value = 0;

    public int getValue() {
        try {
//            lock.readLock().lockInterruptibly();
//            lock.readLock().tryLock();
//            lock.readLock().tryLock(1000L, TimeUnit.MILLISECONDS);
            lock.readLock().lock();
            return value;
        } finally {
            lock.readLock().unlock();
        }
    }

    public void add() {
        try {
//            lock.writeLock().lockInterruptibly();
//            lock.readLock().tryLock();
//            lock.writeLock().tryLock(1000L, TimeUnit.MILLISECONDS);
            lock.writeLock().lock();
            // 先读取
            int temp = value;
            // 为了让实验效果更明显，随机休眠0-1毫秒
            try {
                Thread.sleep(new Random().nextInt(1));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            // 加1后回写
            value = temp + 1;
            System.out.println(String.format("线程%s 前%s 后%s",Thread.currentThread().getName(), temp, value));
        } finally {
            lock.writeLock().unlock();
        }
    }
}
